package com.ly.http;


import com.ly.api.IRAGService;
import com.ly.entity.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RList;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/api/v1/rag/")
public class RAGController implements IRAGService {
    @Resource
    private TokenTextSplitter tokenTextSplitter;

    @Resource
    private PgVectorStore pgVectorStore;

    @Resource
    private RedissonClient redisClient;


    @Override
    @GetMapping("query_rag")
    public Response<Set<String>> queryRAGTagList() {
        RSet<String> set = redisClient.getSet("ragTag");

        return Response.<Set<String>>builder()
                .code("0000")
                .info("调用成功")
                .data(set).build();
    }

    @Override
    @PostMapping(value = "file/upload", headers = "content-type=multipart/form-data")
    public Response<String> uploadFile(String ragTag, List<MultipartFile> files) {
        log.info("正在上传文件至知识库...");
        try {
            for (MultipartFile file : files) {
                TikaDocumentReader documentReader = new TikaDocumentReader(file.getResource());
                List<Document> documents = documentReader.get();
                List<Document> splitDocuments = tokenTextSplitter.split(documents);
                splitDocuments.forEach(v->v.getMetadata().put("knowledge",ragTag));
                //上传知识库
                pgVectorStore.accept(splitDocuments);
                RSet<String> ragSet = redisClient.getSet("ragTag");
                ragSet.add(ragTag);


            }
        } catch (Exception e) {
            log.info("上传失败");
            return Response.<String>builder().code("1111").info("调用失败").build();
        }
        log.info("上传完成");
        return Response.<String>builder().code("0000").info("调用成功").build();
    }
}
